package com.dk.controller;

import com.alibaba.fastjson.JSON;

import com.dk.page.PageResult;
import com.dk.result.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("es")
@Api
@ApiOperation("es搜索")
@RefreshScope//自动刷新配置
public class ESController {

    @Resource
    private RestHighLevelClient client;

    @PostMapping("HighLightQuery")
    @ApiOperation(value = "es多条件查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "车辆名字", required = true, type = "query"),
            @ApiImplicitParam(name = "price", value = "价格(1价格升序,2降序,3价格范围,4)",  type = "query"),
            @ApiImplicitParam(name = "starttime", value = "上架时间(最近时间排序)",  type = "query"),
            @ApiImplicitParam(name = "registered_date", value = "车龄最少",  type = "query"),
            @ApiImplicitParam(name = "mileage", value = "历程最少",  type = "query"),

    })

    public Result HighLightQuery(@RequestParam(required = false) String name ,@RequestParam(defaultValue = "0") String price,@RequestParam(required = false) String starttime,@RequestParam(required = false) String registered_date,@RequestParam(required = false) String mileage){
        try{
            // 搜索请求对象
            SearchRequest searchRequest = new SearchRequest("huasheng");
            //搜索元构建对象
            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
            // Query-match单字段模糊查询
            //模糊查询
            //searchSourceBuilder.query(QueryBuilders.wildcardQuery("name",name));
            //对字段进行升序
            if (!price .equals("0") && price.equals("1")) {
                searchSourceBuilder.sort("price", SortOrder.ASC);
            }
            //对字段进行降序
            if (!price .equals("0") && price.equals("2")) {
                searchSourceBuilder.sort("price", SortOrder.DESC);
            }
            //最新上架
            if (starttime !=null){

                searchSourceBuilder.sort("starttime", SortOrder.DESC);
            }
            //车龄最短
            if (registered_date!=null){
                searchSourceBuilder.sort("registered_date",SortOrder.DESC);
            }
            //历程最少
            if (mileage!=null){
                searchSourceBuilder.sort("registered_date",SortOrder.ASC);
            }
            //范围查询   4万以下
            if (!price .equals("0") && price.equals("3")) {
                searchSourceBuilder.query(QueryBuilders.rangeQuery("price").lt(4));
                if (starttime !=null){

                    searchSourceBuilder.sort("starttime", SortOrder.DESC);
                }
                if (registered_date!=null){
                    searchSourceBuilder.sort("registered_date",SortOrder.DESC);
                }
                //历程最少
                if (mileage!=null){
                    searchSourceBuilder.sort("registered_date",SortOrder.ASC);
                }
            }
            //4-8万
            if (!price .equals("0") && price.equals("4")) {
                searchSourceBuilder.query(QueryBuilders.boolQuery().must(QueryBuilders.rangeQuery("price").lt(8).gt(4)).must(QueryBuilders.matchQuery("name",name)));
                if (starttime !=null){

                    searchSourceBuilder.sort("starttime", SortOrder.DESC);
                }
                if (registered_date!=null){
                    searchSourceBuilder.sort("registered_date",SortOrder.DESC);
                }
                //历程最少
                if (mileage!=null){
                    searchSourceBuilder.sort("registered_date",SortOrder.ASC);
                }
            }
            //8-15万
            if (!price .equals("0") && price.equals("5")) {
                searchSourceBuilder.query(QueryBuilders.boolQuery().must(QueryBuilders.rangeQuery("price").lt(15).gt(8)).must(QueryBuilders.matchQuery("name",name)));
                if (starttime !=null){

                    searchSourceBuilder.sort("starttime", SortOrder.DESC);
                }
                //车龄最短
                if (registered_date!=null){
                    searchSourceBuilder.sort("registered_date",SortOrder.DESC);
                }
                //历程最少
                if (mileage!=null){
                    searchSourceBuilder.sort("registered_date",SortOrder.ASC);
                }
            }
            //15-25万
            if (!price .equals("0") && price.equals("6")) {
                searchSourceBuilder.query(QueryBuilders.boolQuery().must(QueryBuilders.rangeQuery("price").lt(25.0).gt(15.0)).must(QueryBuilders.matchQuery("name",name)));
                if (starttime !=null){

                    searchSourceBuilder.sort("starttime", SortOrder.DESC);
                }
                //车龄最短
                if (registered_date!=null){
                    searchSourceBuilder.sort("registered_date",SortOrder.DESC);
                }
                //历程最少
                if (mileage!=null){
                    searchSourceBuilder.sort("registered_date",SortOrder.ASC);
                }
            }
            //25万以上
            if (!price .equals("0") && price.equals("7")) {
                searchSourceBuilder.query(QueryBuilders.boolQuery().must(QueryBuilders.rangeQuery("price").gt(25.0)).must(QueryBuilders.matchQuery("name",name)));
                if (starttime !=null){

                    searchSourceBuilder.sort("starttime", SortOrder.DESC);
                }
                //车龄最短
                if (registered_date!=null){
                    searchSourceBuilder.sort("registered_date",SortOrder.DESC);
                }
                //历程最少
                if (mileage!=null){
                    searchSourceBuilder.sort("registered_date",SortOrder.ASC);
                }
            }



            ///像搜索请求 对象中设置搜索源
            searchRequest.source(searchSourceBuilder);

            //创建高亮显示对象
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            //设置高亮前缀
            highlightBuilder.preTags("<span style='color:red'>");
            //设置高亮字段
            highlightBuilder.field("name");
            //设置高亮后缀
            highlightBuilder.postTags("</span>");
            //设置添加高亮
            searchSourceBuilder.highlighter(highlightBuilder);
            searchRequest.source(searchSourceBuilder);
            String queryJson = searchSourceBuilder.toString();
            SearchResponse search = client.search(searchRequest, RequestOptions.DEFAULT);
            //搜索结果
            SearchHits hits = search.getHits();

            List list = new ArrayList();
            for (SearchHit hit : hits.getHits()) {
                //使用新的字段值(高亮) 覆盖旧的字段值,源数据
                Map<String, Object> sourceAsMap = hit.getSourceAsMap();
                //高亮字段
                Map<String, HighlightField> highlightFields = hit.getHighlightFields();
                HighlightField ti = highlightFields.get("name");
                //替换
                if (ti != null){
                    //获取当前高亮字段
                    Text[] fragments = ti.fragments();
                    StringBuffer new_name = new StringBuffer();
                    for (Text text : fragments) {
                        new_name.append(text);
                    }
                    sourceAsMap.put("name",new_name.toString());
                    list.add(sourceAsMap);
                }
                System.out.println(sourceAsMap);
            }

            return Result.OK().setData(hits);
        }catch (Exception e){
            e.printStackTrace();
            return Result.ER();
        }
    }



}
